@echo off
setlocal enableextensions

:: Validating arguments passed from Visual Studio to use as variables:
::
:: * Arguments with conflicting syntax can terminate the script abruptly
:: * 'GAS_EXTRA' argument isn't used in some cases
::
set GAS_EXTRA=
for /f "tokens=1,2*" %%A in ('echo %*') do (
set GAS_SRCDIR=%%A
set GAS_OBJDIR=%%B
set GAS_EXTRA=%%C
)
set GAS_CLARG=%GAS_OBJDIR%
if defined GAS_EXTRA set GAS_CLARG=%GAS_OBJDIR% %GAS_EXTRA%

:: "Anti-PEBCAK":
::
:: * Ensures that "Item A" and "Item B" exist, and send an error signal if not
:: * The sole purpose of this code is to make the script fail outside VS
::
if not exist mupen64plus-core.vcxproj exit /b 202
if not exist "%GAS_SRCDIR%asm_defines.c" exit /b 303

:: Legacy code adaptation for this script:
::
:: * Delete the libraries previously generated by 'gawk' or this script
:: * CL's stuff/witchcraft, if all goes well it will generate "Item C"
::
del /f /q "%GAS_SRCDIR%asm_defines_*" 2>nul
cl /c /Fo%GAS_CLARG% /I ..\..\src "%GAS_SRCDIR%asm_defines.c"

:: If "Item C" does not exist, send error
if not exist "%GAS_OBJDIR%asm_defines.obj" exit /b 404
if "%USE_GAWK%" NEQ "1" goto native

:: Legacy code adaptation for 'gawk':
::
:: * Define 'USE_GAWK=1' to use 'gawk'
:: * A POSIX version of 'GAS_SRCDIR' is required for 'dest_dir' argument
::
set "GAS_SRCDIR2=%GAS_SRCDIR:\=/%"
set GAWK=..\..\..\mupen64plus-win32-deps\gawk-3.1.6-1\bin\gawk.exe
"%GAWK%" -v dest_dir="%GAS_SRCDIR2%" -f "%~dp0gen_asm_defines.awk" "%GAS_OBJDIR%asm_defines.obj"
goto log
:native

:: Adaptation of 'gen_asm_defines.awk' / 'gen_asm_script.sh':
::
:: 1. Display 'asm_defines.obj' (aka "Item C") as a list, looking only
::    for patterns '@ASM_DEFINE'
:: 2. Sort for easy reading, the result is interpreted as an array
::    with ' ' as default delimiter in the 'for' command
:: 3. The for's 'tokens=2,3' ignores pattern "1" (@ASM_DEFINE) and anything
::    beyond "3", take "2" (offset* value) as 'J' and "3" (hex* value) as 'K'
:: 4. Print current values and repeat steps 3 and 4 on the next line
::    until EOL is reached
::
for /f "tokens=2,3" %%J in ('type "%GAS_OBJDIR%asm_defines.obj" ^| find "@ASM_DEFINE" ^| sort') do (
echo %%define %%J ^(%%K^)>>"%GAS_SRCDIR%asm_defines_nasm.h"
echo #define %%J ^(%%K^)>>"%GAS_SRCDIR%asm_defines_gas.h"
)
:log

:: Display 'asm_defines_nasm.h' in the log
echo.
type "%GAS_SRCDIR%asm_defines_nasm.h"
echo.
exit /b 0
